package com.itheima.core.service.impl;
import com.itheima.core.dao.RoleDao;
import com.itheima.core.po.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.core.dao.UserDao;
import com.itheima.core.po.User;
import com.itheima.core.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户Service接口实现类
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
	// 注入UserDao
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	// 通过账号和密码查询用户
	@Override
	public User findUser(String usercode, String password) {
		User user = this.userDao.findUser(usercode, password);
		return user;
	}

	@Override
	public List<User> findAllUser() {
		return userDao.findAllUser();
	}

	@Override
	public Integer updateUser(User user) {
		//此处需要修改用户表 用户权限表
		//1.清除用户权限信息
		Integer clearRole = userDao.clearRole(user.getUser_id());
		//2.保存用户基本信息
		Integer updateUser = userDao.updateUser(user);
		//3.保存用户权限信息
		Integer[] roleIds = user.getRoleIds();
		List<UserRole> list = new ArrayList<>();
		for (Integer roleId : roleIds) {
			UserRole userRole = new UserRole();
			userRole.setUser_id(user.getUser_id());
			userRole.setRole_id(roleId);
			list.add(userRole);
		}
		Integer insertRole = userDao.insertRole(list);

		return updateUser;
	}

	@Override
	public User findUserById(Integer id) {
		User userById = userDao.findUserById(id);
		List<UserRole> roleById = userDao.findRoleById(id);
		List roleList = new ArrayList();
		for (UserRole userRole : roleById) {
			roleList.add(userRole.getRole_id());
		}
		Integer[] roles = new Integer[10];
		for (int i = 0; i < roleList.size(); i++) {
			roles[i] = (Integer) roleList.get(i);
		}
		userById.setRoleIds(roles);
		return userById;
	}
}
